package com.atguigu.daijia.rules.service.impl;

import com.atguigu.daijia.model.entity.rule.RewardRule;
import com.atguigu.daijia.model.form.rules.RewardRuleRequest;
import com.atguigu.daijia.model.form.rules.RewardRuleRequestForm;
import com.atguigu.daijia.model.vo.rules.RewardRuleResponse;
import com.atguigu.daijia.model.vo.rules.RewardRuleResponseVo;
import com.atguigu.daijia.rules.config.DroolsHelper;
import com.atguigu.daijia.rules.mapper.RewardRuleMapper;
import com.atguigu.daijia.rules.service.RewardRuleService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.kie.api.runtime.KieSession;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;

@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
@RequiredArgsConstructor
public class RewardRuleServiceImpl implements RewardRuleService {

    // 使用本地规则 src/main/resources/rules/RewardRule.drl
    private static final String REWARD_RULE_DRL = "rules/RewardRule.drl";
    // 从 daijia_rule 数据库 reward_rule 表中获取规则
    private final RewardRuleMapper rewardRuleMapper;

    /**
     * 计算订单的系统奖励
     *
     * @param rewardRuleRequestForm
     * @return
     */
    @Override
    public RewardRuleResponseVo calculateOrderRewardFee(RewardRuleRequestForm rewardRuleRequestForm) {
        // 封装规则引擎计算订单的系统奖励需要传入的参数
        RewardRuleRequest rewardRuleRequest = new RewardRuleRequest();
        rewardRuleRequest.setOrderNum(rewardRuleRequestForm.getOrderNum());
        // 获取订单的开始时间字符串
        String startTime = new SimpleDateFormat("HH:mm:ss").format(rewardRuleRequestForm.getStartTime());
        rewardRuleRequest.setStartTime(startTime);

        // 加载本地规则
        // KieSession kieSession = DroolsHelper.loadForRule(REWARD_RULE_DRL);
        // 从数据库获取最新系统奖励规则
        RewardRule rewardRule = rewardRuleMapper.selectOne(new LambdaQueryWrapper<RewardRule>()
                .eq(RewardRule::getStatus, 1)
                .orderByDesc(RewardRule::getId)
                .last("limit 1"));
        KieSession kieSession = DroolsHelper.loadForRule(rewardRule.getRule());

        // 设置规则引擎的全局参数，用于规则引擎计算后，返回结果
        RewardRuleResponse rewardRuleResponse = new RewardRuleResponse();
        kieSession.setGlobal("rewardRuleResponse", rewardRuleResponse);

        // 设置对象，触发规则
        kieSession.insert(rewardRuleRequest);
        kieSession.fireAllRules();

        // 终止规则引擎
        kieSession.dispose();

        // 封装返回结果
        RewardRuleResponseVo rewardRuleResponseVo = new RewardRuleResponseVo();
        rewardRuleResponseVo.setRewardAmount(rewardRuleResponse.getRewardAmount());
        rewardRuleResponseVo.setRewardRuleId(rewardRule.getId());
        return rewardRuleResponseVo;
    }
}
